<template>
  <j-modal
    title="上传资源"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    switchFullscreen
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭"
    :footer="customFooter"
  >
    <a-spin :spinning="confirmLoading">
      <div class="table-page-search-wrapper">
        <a-form-model layout="inline" ref="form" :model="model" :rules="validatorRules">
          <a-row :gutter="24" style="margin-left: 4px;">
            <a-col :xl="10" :lg="10" :md="8" :sm="24">
              <a-form-model-item prop="projectName" label="所属项目">
                <a-select
                  show-search
                  placeholder="搜索下拉"
                  v-model="model.projectName"
                  @search="searchChange('1', $event)"
                  @change="upchange"
                  option-filter-prop="children"
                  :filter-option="filterOption"
                >
                  <a-select-option v-for="item in uplist" :key="item.id">{{ item.projectName }}</a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :xl="10" :lg="10" :md="8" :sm="24">
              <a-form-model-item prop="folderName" label="所属文件夹">
                <a-select
                  show-search
                  placeholder="搜索下拉"
                  v-model="model.folderName"
                  @search="searchChange('1', $event)"
                  option-filter-prop="children"
                  :filter-option="filterOption"
                >
                  <a-select-option v-for="item in datalist" :key="item.id">{{ item.folderName }}</a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :xl="20" :lg="20" :md="8" :sm="24">
              <div style="height: 230px;">
                <a-form-model-item prop="uploads" label="选择上传资源">
                  <a-upload-dragger
                    name="file"
                    action=""
                    accept='".png, .jpg, .jpeg, .gif, .bmp, .dib, .pcp, .dif, .iff, .wmf, .tif, .eps, .psd, .cdr, .tga, .pcd, .mpt,.mp4, .avi, .wmv, .wmv, .mpg, .mpeg, .mov, .swf, .flv, .rm, .ram,.mp3, .wav, .aif, .aiff, .au, .mp1, .mp2, .ra, .mid, .rmi,.doc, .docx, .xls, .xlsx, .ppt, .pptx, .pdf, .mdf, .txt, .tif, .tiff,.rar,.zip"'
                    :multiple="false"
                    :beforeUpload="handleUpload"
                    :customRequest="handleBeforeUpload"
                    :remove="handleRemove"
                    :fileList="fileList"
                  >
                    <p class="ant-upload-drag-icon">
                      <a-icon type="cloud-upload" />
                    </p>
                    <p class="ant-upload-text">
                      将资源拖到此处，或<span style="color: rgb(107, 189, 255);">点击上传</span>
                    </p>
                  </a-upload-dragger>
                </a-form-model-item>
              </div>
            </a-col>
          </a-row>
          <a-row>
            <a-col :xl="3" :lg="5" :md="8" :sm="24"></a-col>
            <a-col :xl="15" :lg="15" :md="8" :sm="24">
              &nbsp;&nbsp; <span v-if="fileList == []">能支持人部分常见文件资源，建议大小不超过100MB</span>
            </a-col>
          </a-row>
        </a-form-model>
      </div>
    </a-spin>
  </j-modal>
</template>

<script>
import { httpAction, getAction, uploadAction, postAction } from '@/api/manage'
import moment from 'moment'
import SparkMD5 from 'spark-md5'
export default {
  name: 'BusTreviRiverPcModal',

  data() {
    return {
      title: '操作',
      visible: false,
      model: {},
      value: '',
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },

      confirmLoading: false,
      validatorRules: {
        userId: [{ required: true, message: '请输入用户id!' }]
      },
      url: {
        add: '/resource/busResource/add',
        edit: '/sensitiveWord/busSensitiveWord/edit',
        pjtselect: '/bus/busProject/projectNameList', //所有项目
        busFolder: '/bus/busFolder/folderNameList', //所属文件夹
        upload: '/file/Upload/breakpointContinuation',
        uploads: '/file/Upload/upload',
        cancelUpload : '/file/Upload/cancelUpload'
      },
      validatorRules: {
        projectName: [{ required: true, message: '请选择所属项目' }],
      },
      fileList: [],
      uplist: [],
      datalist: [],
      isupload: true,
      fileVo:[]
    }
  },
  created() {
    this.uploadlist()
    //在这里进行刷新数据
    // this.uploaddata()
  },
  methods: {
    customFooter(){
      return (
        <span class="custom-button">
            <a-button onClick={this.cancel}>关闭</a-button>
          <a-button type="primary" onClick={this.sumbitData}>确定</a-button>
        </span>
      );
    },
    add() {
      if(this.uplist.length===0){
        this.$message.warning('当前还没有项目，点击我创建项目')
         setTimeout(()=>{
           this.$emit('oMethod',null)
         },500);
      }else {
        //初始化默认值
        if (this.model.projectName == null) {
          this.edit({})
        } else {
          this.uploaddata(this.model.projectName, 'type')
        }
        this.visible = true
      }
    },
    edit(record) {
      this.model = Object.assign({}, record)
      this.visible = true
    },
    close() {
      this.$emit('close')
      this.visible = false
      this.$refs.form.clearValidate()
    },
    handleOk() {
      const that = this
      this.fileList = []
      // 触发表单验证
      this.$refs.form.validate(valid => {
        if (valid) {
        }
      })
    },
    //所属项目下拉
    uploadlist(name) {
      const httpurl = this.url.pjtselect
      const method = 'get'
      const params = { projectNidame: name }
      getAction(httpurl, params, method).then(res => {
        this.uplist = res.result
      })
    },
    //所属文件下拉
    uploaddata(name, type) {
      const httpurl = this.url.busFolder
      const method = 'get'
      let params
      if (type == type) {
        params = { projectId: name }
      } else {
        params = { folderName: name }
      }

      getAction(httpurl, params, method).then(res => {
        this.datalist = res.result
      })
    },
    upchange(e) {
      this.uploaddata(e, 'type')
    },
    setValue(busFolderVo) {

      const obj = {
        folderName: busFolderVo.id,
        projectName: busFolderVo.projectId
      }
      this.model = Object.assign({},obj)//Object.assign方法可以拷贝对象
    },
    searchChange(type, e) {
      if (type == 1) {
        this.uploadlist(e)
      } else if (type == 2) {
        this.uploaddata(e)
      }
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    handleCancel() {
      this.close()
    },
    //文件上传
    async handleUpload(file, filelist) {
      this.fileList = [...this.fileList, file]
      console.log(this.fileList, '===================')
      if (this.model.projectName == undefined && this.model.folderName == undefined) {
        this.$message.warn('请选择所属项目!')
        this.fileList = []
      } else {
        const SIZE = 1024 * 1024 // 切片大小
        const total = Math.ceil(file.size / SIZE) // 总片数
        const Md5 = await this.getFileMd5(file, total)
        const formData = new FormData()
        formData.append('multipartFile', file)
        formData.append('fileMd5', Md5)
        formData.append('projectId', this.model.projectName)
        formData.append('folderId', this.model.folderName)
        const httpurl = this.url.uploads
        //请求接口
        uploadAction(httpurl, formData).then(res => {
          if(res.code == 200)
          {
            this.fileVo=res.result;

          }
        })
      }
    },
    //提交文件
    sumbitData() {

      // console.log(this.$parent.$parent.resList(),'parent');
      // return
      const httpurl = this.url.add;
      //请求接口
      if (this.fileVo.length==0) {
        this.$message.error('请选择所属项目和所属文件夹，上传文件');
      } else {
        postAction(httpurl, this.fileVo).then(res => {
          if (res.success) {
            this.$message.success('上传成功！');

              // this.$parent.$parent.resList()
            //重新加载列表
             this.$emit('resourceNameList');
             this.$emit('resource')
            this.fileList = []
            this.close();

          }
        })
      }
    },
    //取消提交
    cancel(){
      const httpurl = this.url.cancelUpload;
      if (this.fileVo.fileId==null||this.fileVo.fileId==''){
        this.close();
      }else {
        postAction(httpurl,this.fileVo).then(res=>{
          if (res.success){
            this.fileList = []
            this.$message.success('取消成功！');
            this.close();
          }else {
            this.$message.error('取消失败！');
          }
        })
       }
      },
    //文件加密
    getFileMd5(file, chunkCount) {
      return new Promise((resolve, reject) => {
        let blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice
        let chunks = chunkCount
        let currentChunk = 0
        let spark = new SparkMD5.ArrayBuffer()
        let fileReader = new FileReader()
        fileReader.onload = function(e) {
          spark.append(e.target.result)
          currentChunk++
          if (currentChunk < chunks) {
            loadNext()
          } else {
            let md5 = spark.end()
            resolve(md5)
          }
        }
        fileReader.onerror = function(e) {
          reject(e)
        }
        function loadNext() {
          const chunkSize = 1024 * 1024
          let start = currentChunk * chunkSize
          let end = start + chunkSize
          if (end > file.size) {
            end = file.size
          }
          fileReader.readAsArrayBuffer(blobSlice.call(file, start, end))
        }
        loadNext()
      })
    },
    handleBeforeUpload({ file, onSuccess, onError }) {},
    handleRemove(file) {
      const index = this.fileList.indexOf(file)
      this.fileList.splice(index, 1)
    }
  }
}
</script>

<style lang="less" scoped>
/deep/ .ant-upload-drag {
  height: 200px;
}
</style>
